package org.yun.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.Executor;


/**
 * @author liyunfeng31
 * 添加 @EnableNacosConfig 注解启用 Nacos Spring 的配置管理服务，serverAddr配置nacos server地址
 * 使用 @NacosPropertySource 加载了 dataId 为 tangBoHo 的配置源，并启用自动刷新
 */
@Data
@Slf4j
@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "tangBoHo",autoRefreshed = true)
public class NacosConfig implements IConfig {

    /**
     * 触发nacosConfigPublishedEvent回调
     */
    @NacosInjected
    private ConfigService configService;

    @NacosValue(value = "${activity:null}", autoRefreshed = true)
    private String activity;

    @NacosValue(value = "${snapshotswitch:true}", autoRefreshed = true)
    private Boolean snapshotswitch;

    @NacosValue(value = "${asynswitch:true}", autoRefreshed = true)
    private Boolean asynswitch;

    @NacosValue(value = "${nostockskulist:null}", autoRefreshed = true)
    private String nostockskulist;

    @NacosValue(value = "${test:222}", autoRefreshed = true)
    private String test;

    @Override
    public String configs() {
        try {
            return configService.getConfig("tangBoHo", "DEFAULT_GROUP", 3000);
        } catch (NacosException e) {
            log.error("get all cfg from nacos error",e);
        }
        return null;
    }

    @Override
    public void publishConfig(String keyVal) {
        try {
            String[] arr = keyVal.split("=");
            StringBuilder sb = new StringBuilder();
            String[] cfgList = this.configs().split("\n");
            for (String s : cfgList) {
                String[] kv = s.split("=");
                if(kv[0].equals(arr[0])){
                    sb.append(kv[0]).append("=").append(arr[1]);
                }else{
                    sb.append(s);
                }
                sb.append("\n");
            }
            log.info("nacos publish config, target kv is: {}, all content is: {}", keyVal, sb);
            configService.publishConfig("tangBoHo", "DEFAULT_GROUP", sb.toString());
        } catch (NacosException e) {
            log.error("nacos publish config error, param: {}", keyVal,e);
        }
    }

    @Override
    public String getActivity(Long lotteryId) {
        // todo
        return activity;
    }

    @Override
    public boolean getSnapshotSwitch() {
        return snapshotswitch;
    }

    @Override
    public boolean getAsynSwitch() {
        return asynswitch;
    }

    @Override
    public <T> List <T> getNoStockSkuList(Class<T> clz) {
        List<T> list = JSON.parseArray(nostockskulist, clz);
        return Optional.ofNullable(list).orElse(new ArrayList<>());
    }



    public static void main(String[] args) throws NacosException, InterruptedException {
        String serverAddr = "localhost";
        String dataId = "AAA";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        boolean isPublishOk = configService.publishConfig(dataId, group, "sku=123\ntest=33333333");
        System.out.println(isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);

        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println(isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        Thread.sleep(300000);

    }
}